﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace IngressLinker
{
    public delegate void ChangedEventHandler(List<Point> sender);
    class Controller
    {
        private string _lastFile = "";
        public event ChangedEventHandler Changed;

        public void LoadFile()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            //dlg.DefaultExt = ".png";
            //dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
            Nullable<bool> result = dlg.ShowDialog();
            
            if (result == true)
            {
                _lastFile = dlg.FileName;
                LoadSingleFile(dlg.FileName);
            }
        }

        public void ReloadFile()
        {
            LoadSingleFile(_lastFile);
        }

        private void Parse(List<string> coordinates)
        {
            List<Point> trueList = new List<Point>();
            foreach (string s in coordinates)
            {
                string[] points = s.Remove(0, s.IndexOf("pll=") + 4).Split(new[] { ',' });//48.456982,34.971693
                NumberFormatInfo provider = new NumberFormatInfo();
                provider.NumberDecimalSeparator = ".";
                Point p = new Point(Convert.ToDouble(points[0], provider), Convert.ToDouble(points[1], provider));
                trueList.Add(p);
            }
            Changed(trueList);
        }

        private void LoadSingleFile(string filename)
        {
            List<string> coordinates = new List<string>();
            StreamReader streamReader = new StreamReader(filename);
            string lineOfText;
            while ((lineOfText = streamReader.ReadLine()) != null)
            {
                coordinates.Add(lineOfText);
            }
            streamReader.Close();
            Parse(coordinates);
        }
    }
}
